<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/7
// +----------------------------------------------------------------------

namespace app\index\controller\api;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\common\facade\TransItem;
use app\common\services\JobOptionService;
use app\common\services\JobService;
use app\common\services\PublishJobService;
use app\common\services\UserService;
use app\common\validate\JobValidate;
use Carbon\Carbon;
use Matrix\Exception;
use think\App;
use think\Db;
use think\facade\Validate;

/**
 *
 * Class Jobs
 * @package app\index\controller\api
 * @author feraner<feraner@163.com>
 * @date 2019/11/7
 */
class Jobs extends ApiBase
{

    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }


    /**
     * 兼职列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $postData = $this->request->param();

        //地区
        if ($areaValue = Arr::get($postData, 'areaValue', '')) {
            $areaArr = array_filter(explode('|', str_replace(['镇', '县', '乡', '村', '庄', '市','省'], '', $areaValue)));
            if (Arr::get($areaArr, 0, '')) {
                $provincesId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Arr::get($areaArr, 0) . '%')
                    ->where('area_deep', 1)
                    ->value('area_id') ?: 0;
                if ($provincesId) {
                    $postData['provincesId'] = $provincesId;
                }
            }
            if (Arr::get($areaArr, 1)) {
                $cityId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Arr::get($areaArr, 1) . '%')
                    ->where('area_deep', 2)
                    ->where('area_parent_id', Arr::get($postData, 'provincesId', 0))
                    ->value('area_id') ?: 0;
                if ($cityId) {
                    $postData['cityId'] = $cityId;
                }
            }
            if (Arr::get($areaArr, 2)) {
                $countyId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Arr::get($areaArr, 2) . '%')
                    ->where('area_deep', 3)
                    ->where('area_parent_id', Arr::get($postData, 'cityId', 0))
                    ->value('area_id') ?: 0;
                if ($countyId) {
                    $postData['countyId'] = $countyId;
                }
            }
            $postData = $this->checkLocationInSystem($postData);
        }
        //tag
        if ($tagValue = Arr::get($postData, 'tagValue', '')) {
            $tagId = Db::name('tag')
                ->where('tag_name', $tagValue)
                ->where('type', 1)
                ->value('id') ?: 0;
            if ($tagId) {
                $postData['tagId'] = $tagId;
            }
        }

        $jobList = (new JobService())->jobList(
            $postData,
            Arr::get($postData, 'page'),
            Arr::get($postData, 'pageSize'),
            []
        );

        $this->response([
            'jobList'          => $jobList
        ]);
    }




    /**
     * 兼职详情
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $jobId = $this->request->param('id');
        $extend = $this->request->param('extend', 'content', 'trim');
        $extend = array_filter(explode(',', $extend));
        if ($jobId) {
            $jobInfo = (new JobService())->jobDetail($jobId, $extend);
            if ($jobInfo) {
                $jobInfo['applyOption'] = !(new JobOptionService())->checkUserApply($this->userId, $jobId);
                $jobInfo['userCollect'] = (new UserService())->isCollect($jobId, $this->userId, 1);
                Db::name('jobs')
                    ->where('id', $jobId)
                    ->setInc('click_num');
                $this->response($jobInfo);
            }
            $this->response(
                [],
                ApiConstant::JOB_NOT_FUND_ERROR,
                ApiConstant::JOB_NOT_FUND_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    public function jobSelectCommon()
    {
        $settlementList = TransItem::transSettlement();
        $genderList = TransItem::transGender();

        $this->response([
            'settlementList'        => $settlementList,
            'genderList'            => $genderList
        ]);
    }


    public function jobSettlement()
    {
    }






    /**
     * 兼职类型列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function jobTypeList()
    {
        $limit = $this->request->param('limit', 0);

        $typeListDb = Db::name('jobs_type')
            ->where('status', 1);
        if ($limit) {
            $typeListDb->limit(0, $limit);
        }

        $typeList = $typeListDb->order('sort', 'ASC')
            ->select() ?: [];
        if ($typeList) {
            $this->response($typeList);
        }
        $this->response([], ApiConstant::JOB_TYPE_IS_NOT_FUND, ApiConstant::JOB_TYPE_IS_NOT_FUND_STR);
    }



    /**
     * 发布兼职需要的信息选项
     */
    public function publishNeedData()
    {
        $gender = TransItem::transGender();
        $settlement = TransItem::transSettlement();
        $moneyUnit = TransItem::transMoneyUnit();

        $this->response([
            'gender'        => $gender,
            'settlement'    => $settlement,
            'moneyUnit'     => $moneyUnit,
        ]);
    }


    /**
     * 保存为草稿
     */
    public function saveJobDraft()
    {
        $postData = $this->request->post();
        $jobValidate = new JobValidate();
        if ($jobValidate->check($postData)) {
            $postData = array_merge(
                $postData,
                [
                    'user_id'       => $this->userId,
                    'business_id'   => 0,
                    'status'        => 0,
                    'admin_id'      => 0,
                ]
            );
            $result = (new PublishJobService())->saveJobDraft($postData);
            if ($result) {
                $this->response(
                    $result,
                    ApiConstant::API_SUCCESS,
                    ApiConstant::API_SUCCESS_STR
                );
            }
            $this->response(
                [],
                ApiConstant::JOB_SAVE_DRAFT_ERROR,
                ApiConstant::JOB_SAVE_DRAFT_ERROR_STR
            );
        } else {
            $this->response(
                [],
                ApiConstant::JOB_PARAMETER_NOT_PASS,
                ApiConstant::JOB_PARAMETER_NOT_PASS_STR . $jobValidate->getError()
            );
        }
    }


    /**
     * 用户前端发布兼职
     */
    public function publishJob()
    {
        $postData = $this->request->post();
        $jobValidate = new JobValidate();
        if ($jobValidate->check($postData)) {
            $postData = array_merge(
                $postData,
                [
                    'user_id'       => $this->userId,
                    'business_id'   => 0,
                    'status'        => 1,
                    'admin_id'      => 0,
                ]
            );
            try {
                $result = (new PublishJobService())->publishJob($postData);
                if ($result) {
                    $this->response(
                        $result,
                        ApiConstant::API_SUCCESS,
                        ApiConstant::API_SUCCESS_STR
                    );
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    $e->getCode(),
                    ApiConstant::JOB_PUBLISH_ERROR_STR . $e->getMessage()
                );
            }
        } else {
            $this->response(
                [],
                ApiConstant::JOB_PARAMETER_NOT_PASS,
                ApiConstant::JOB_PARAMETER_NOT_PASS_STR . $jobValidate->getError()
            );
        }
    }


    /**
     * 审核用户发布的兼职
     */
    public function auditJob()
    {
        $jobId = $this->request->post('jobId', 0);
        $pass = $this->request->post('pass', 0);
        $message = $this->request->post('message', '内容敏感');
        if ($jobId && $pass) {
            try {
                $publishJobService = new PublishJobService();
                $status = 1;
                if ($pass == 1) {
                    //审核同意
                    $result = $publishJobService->approvedJob($jobId, $this->userId);
                    $status = 2;
                } else {
                    //拒绝
                    $result = $publishJobService->rejectJob($jobId, $this->userId, $message);
                    $status = 3;
                }
                if ($result) {
                    $this->response([
                        'pass'    => $pass,
                        'status'  => $status
                    ]);
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::JOB_AUDIT_ERROR,
                    ApiConstant::JOB_AUDIT_ERROR_STR . ':' . $e->getMessage()
                );
            }
            $this->response(
                [],
                ApiConstant::JOB_AUDIT_ERROR,
                ApiConstant::JOB_AUDIT_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 用户申请参加该兼职
     */
    public function applyJob()
    {
        $jobId = $this->request->post('id');
        if ($jobId) {
            try {
                $result = (new JobOptionService())->userApplyJob($jobId, $this->userId);
                if ($result) {
                    $this->response($result);
                } else {
                    $this->response(
                        [],
                        ApiConstant::JOB_APPLY_ERROR,
                        ApiConstant::JOB_APPLY_ERROR_STR
                    );
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    $e->getCode(),
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 搜索兼职
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function searchJob()
    {
        $searchValue = $this->request->post('searchValue', '', 'trim');
        $city = $this->request->post('city', '');
        if ($searchValue) {
            $cityId = 0;
            if ($city) {
                $cityId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . $searchValue . '%')
                    ->where('area_deep', 2)
                    ->value('area_id') ?: 0;
            }
            $jobList = (new JobService())->jobList(
                [
                    'cityId'        => $cityId,
                    'searchTitle'   => $searchValue
                ],
                1,
                10
            );
            if ($jobList) {
                $this->response($jobList);
            }
            $this->response([], ApiConstant::JOB_SEARCH_ERROR, ApiConstant::JOB_SEARCH_ERROR_STR);
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 获取该条兼职置顶需要消耗的发布豆
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTopJobNeedBean()
    {
        $jobId = $this->request->param('jobId', 0);
        $jobInfo = Db::name('jobs')
            ->where('id', $jobId)
            ->where('is_deleted', 0)
            ->field('id,provinces_id,city_id,county_id')
            ->find() ?: [];
        if ($jobId && $jobInfo) {
            $agentInfo = Db::name('system_agent_user')
                ->where('pid', 0)
                ->where('provinces_id', Arr::get($jobInfo, 'provinces_id'))
                ->where('city_id', Arr::get($jobInfo, 'city_id'))
                ->where('is_deleted', 0)
                ->where('status', 1)
                ->find() ?: [];
            if ($agentInfo) {
                $result = Db::name('bean')
                    ->where('aid', Arr::get($agentInfo, 'id'))
                    ->field('id,aid,job_top')
                    ->find() ?: [];
                $this->response($result);
            } else {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    ApiConstant::API_ERROR_STR
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }









}
